<?php
namespace app\common\process;

use think\exception\ValidateException;

class SubsidiaryMany extends Subsidiary {

    //获取从信息编辑
    public function info($user) {
    	$model = $this->model;
        $validate = $this->validate;

    	$pk = input('param.' . $this->pk);
        $ownerPk = input('param.' . $this->ownerPk);
        
        $this->validate_info($ownerPk, $user);

        $row = null;
        if($pk) {
            $row = $model->find($pk);
            if(empty($row)) {
                throw new ValidateException('信息数据不存在');
            }
        }
        $this->assign($this->pk, $pk);
        $this->assign($this->ownerPk, $ownerPk);
        $this->assign($this->row, $row);
        return $this->fetch();
    }

    //保存从信息
    public function save($user) {
    	$model = $this->model;
    	$validate = $this->validate;
        $pk = $this->pk;
        $ownerPk = $this->ownerPk;

        $post = $this->post($user);

        if (!$validate->check($post)) {
        	throw new ValidateException($validate->getError());
        }
        if(isset($post[$pk]) && $post[$pk]) {
            $model->allowField($this->field)->save($post, [$ownerPk => $post[$ownerPk], $pk => $post[$pk]]);
        } else {
            $model->allowField($this->field)->save($post);
        }
        $this->assign($pk, $model->$ownerPk);
        return $this->fetch();
    }

    //删除从信息
    public function del($user) {
        $model = $this->model;
    	$validate = $this->validate;
        $pk = $this->pk;
        $ownerPk = $this->ownerPk;

		$post = $this->post($user);

        if (!$validate->scene($this->delScene)->check($post)) {
            throw new ValidateException($validate->getError());
        }
        $model->where([$this->ownerPk => $post[$ownerPk], $this->pk => $post[$pk]])->delete();
        $this->assign($pk, $post[$ownerPk]);
        return $this->fetch(); 
    }
}